-- Client side just does the view model stuff, everything else is server side,
local meta = FindMetaTable( "Player" )
if !meta then error( "NO FUCKING META TABLE!!!" ) end

function meta:Cloak()

	if self:Team() == TEAM_HIDE then
		self:SetVar( "IsCloaked", true )
		self:SetVar( "targetAlpha", 15 )	
	end
	
end

function meta:UnCloak()

	self:SetVar( "IsCloaked", false )
	self:SetVar( "targetAlpha", 255 )		

end

function GM:Initialize()

	local ply = LocalPlayer()
	
	ply:SetVar( "IsCloaked", false )
	ply:SetVar( "targetAlpha", 255 )	

end

-- Helper function too set a players alpha.
function updatePlayerAlpha( alpha )

	local ply = LocalPlayer()

	if ply:Team() ~= TEAM_HIDE then return false end
	
	-- Cloak the players world model.
	local vmodel = ply:GetViewModel()
	
	if vmodel && vmodel:IsValid() then
		vmodel:SetColor( 255, 255, 255, alpha )
	end
	
	-- Set the current alpha
	ply:SetVar( "curAlpha", alpha )

end

function cloakThink()

	local ply = LocalPlayer()

	local alpha = ply:GetVar( "curAlpha", 255 )
	local targetAlpha = ply:GetVar( "targetAlpha", 255 )
	
	-- Do the actual calculations.
	if targetAlpha && ply:Team() == TEAM_HIDE then
		
		local newAlpha
		
		if alpha != targetAlpha then
				
			newAlpha = math.Approach( alpha, targetAlpha, 10 ) -- Half of server running twice as fast. 
		
		else
		
			newAlpha = targetAlpha
		
		end
		
		-- Do it!
		updatePlayerAlpha( newAlpha )
	
	else
	
		updatePlayerAlpha( 255 )
		
	end
	
end
timer.Create( "cloakThink", 0.05, 0, cloakThink )

function CloakSync( um )

	local ply = LocalPlayer()
	local cloaked = um:ReadBool()
	local curAlpha = um:ReadShort()
	local targAlpha = um:ReadShort()
	
	ply:SetVar( "IsCloaked", cloaked )
	ply:SetVar( "curAlpha", curAlpha )
	ply:SetVar( "targetAlpha", targAlpha )
		
end
usermessage.Hook( "CloakSync", CloakSync )
